<template>
  <div>
    <TopFilter :list="topFilterList" :labelWidth="140" :cols="3" :rows="2" @filterChange="changeHandle" @onCollapse="collapseHandle" />

    <FilterTable
      ref="lackDetailTable"
      columnsRef="partPartOtherQrCodeActivationIndex"
      :columns="columns"
      :datakey="'rows'"
      :dataSource="tableDataList"
      :isMemoryPagination="true"
      :onRowSelectChange="columns => (this.partColumns = columns)"
      :onColumnsChange="columns => (this.columns = columns)"
      selectionType="single"
      :isExportExcel="true"
      :onSyncTableData="asyncTableData"
      exportFileName="配件二维码激活.xlsx"
    >
      <!-- :fetchapi="fetchApi"
      :params="fetchParams" -->
      <template slot="controls">
        <!-- <AjaxButton size="small" type="primary" :click="saveClick">保存</AjaxButton> -->
        <AjaxButton type="primary" :click="activateHandle">激活二维码</AjaxButton>
        <AjaxButton type="primary" :click="deactivateHandle">取消激活</AjaxButton>
        <!-- <AjaxButton size="small" icon="el-icon-download" type="primary" :click="() => {}">导出</AjaxButton> -->
      </template>
    </FilterTable>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { listQRCode, activateQRCode, deactivateQRCode } from '@/api/part/partOther/qrCodeActivation';
import { getAllUser } from '@/api/customerRepair/afterSaleVisit/resultEntry';
import dictCode from '@/utils/dictCode';
import moment from 'moment';
export default {
  name: 'lackDetail',
  mixins: [dictionary],
  data() {
    return {
      topFilterList: this.createTopFilterList(),
      fetchParams: {
        xhrAbort: true
      },
      columns: this.createTableColumns(),
      fetchApi: listQRCode,
      partColumns: [],
      serviceAdvisorData: [],
      tableDataList: [], // 修改为内存分页
      asyncData: [], //
      lockData: [] // 禁用数据
    };
  },
  mounted() {
    this.getQueryBookingInformation();
    this.BaseTable = this.$refs.lackDetailTable.$refs.pageTable;
  },
  created() {
    this.getStorage();
  },
  methods: {
    // 同步表单数据
    asyncTableData(list, isFirst) {
      if (isFirst && list.length > 0) {
        setTimeout(() => {
          this.BaseTable.SET_CELL_UNEDITABLE(this.lockData, 'BarCode', true);
        });
      }
    },
    // 设置单元格是否可编辑
    setEditable(val) {
      this.BaseTable.SET_CELL_UNEDITABLE(val, 'BarCode', true);
    },
    // 判断是否选中
    checkSelect() {
      if (this.partColumns.length < 1) {
        throw this.$notify.error({ title: '提示信息', message: '请选中一条数据' });
      }
      // if (!this.partColumns[0]['ActivationFlag']) {
      //   throw this.$notify.error({ title: '提示信息', message: '请填写激活标志' });
      // }
    },
    // 配件激活按钮
    async activateHandle() {
      // 校验
      this.checkSelect();
      if (this.partColumns[0].ActivationFlag == '10041001') {
        return this.$notify.warning({ title: '提示信息', message: '已经激活的配件不允许重复激活' });
      }
      const listErr = await this.BaseTable.GET_REQUIRED_ERROR();
      if (listErr !== '' && listErr !== undefined && listErr !== null) {
        return this.$notify.error({ title: '提示信息', message: listErr.message });
      }
      let params = Object.assign({}, this.partColumns[0], { ActivationFlag: '10041001' });
      // console.log('激活数据', params);
      let res = await activateQRCode(params);
      if (res.resultCode == 200) {
        this.partColumns[0].ActivationFlag = res.data;
        this.$notify.success({ title: '提示信息', message: '激活成功' });
        // this.tableDataList = [...this.tableDataList];
        // this.columns = [...this.columns];
      }
    },
    // 配件取消激活按钮
    async deactivateHandle() {
      // 校验
      this.checkSelect();
      const listErr = await this.BaseTable.GET_REQUIRED_ERROR();
      if (listErr !== '' && listErr !== undefined && listErr !== null) {
        return this.$notify.error({ title: '提示信息', message: listErr.message });
      }
      let params = Object.assign({}, this.partColumns[0], { ActivationFlag: '10041002' });
      let res = await deactivateQRCode(params);
      if (res.resultCode == 200) {
        this.partColumns[0].ActivationFlag = res.data;
        this.$notify.success({ title: '提示信息', message: '取消激活成功' });
      }
    },
    // 创建表单数据
    createTopFilterList() {
      return [
        {
          type: 'RANGE_DATE',
          label: '出库日期',
          fieldName: 'outDateStart|outDateEnd',
          initialValue: [
            moment()
              .startOf('month')
              .format('YYYY-MM-DD'),
            moment().format('YYYY-MM-DD')
          ]
        },
        {
          type: 'INPUT',
          label: '对应单编号',
          fieldName: 'BillNo'
          //   placeholder: '请输入配件代码'
        },
        {
          type: 'SELECT',
          label: '单据类型',
          fieldName: 'documentType',
          // placeholder: '请选择工单类型',
          itemList: [
            { text: '委托书', value: '1' },
            { text: '配件销售单', value: '2' },
            { text: '兑奖单', value: '3' }
          ]
        },
        {
          type: 'CHECKBOX',
          label: '包含停用二维码配件',
          fieldName: 'partStatus',
          initialValue: '',
          options: {
            trueValue: '10041002',
            falseValue: '10041001'
          }
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'CustomerName'
          //   placeholder: '请选择结案状态',
          //   itemList: this.createDictList('8060')
        },
        {
          type: 'INPUT',
          label: '牌照号',
          fieldName: 'license'
        },
        {
          type: 'INPUT',
          label: '底盘号',
          fieldName: 'Vin'
          //   placeholder: '请选择结案状态',
          //   itemList: this.createDictList('8060')
        },
        {
          type: 'SELECT',
          label: '激活状态',
          fieldName: 'ActivationFlag',
          itemList: [
            { text: '待激活', value: '10041002' },
            { text: '已激活', value: '10041001' }
          ]
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          },
          sorter: true
        },
        {
          title: '对应单编号',
          dataIndex: 'BillNo',
          width: 120,
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'PartCode',
          //   editable: true,
          //   editType: 'select',
          filter: true,
          filterType: 'input',
          width: 120,
          showOverflowTooltip: true
        },
        {
          title: '配件名称',
          dataIndex: 'partName',
          width: 150,
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '二维码',
          dataIndex: 'BarCode',
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'input',
          // editRequired: true,
          showOverflowTooltip: true
          // editDisableRender: props => {
          //   return <el-input value={props.row.BarCode} disabled={props.row.ActivationFlag == '10041001' ? true : false}></el-input>;
          // }
        },
        {
          title: '激活标识',
          dataIndex: 'ActivationFlag',
          filter: true,
          filterType: 'checkbox',
          filterItems: [
            { text: '待激活', value: '10041002' },
            { text: '已激活', value: '10041001' }
          ],
          dictItems: [
            { text: '待激活', value: '10041002' },
            { text: '已激活', value: '10041001' }
          ],
          // editable: true,
          // editType: 'select',
          // editRequired: true,
          // editItems: [
          //   { text: '待激活', value: '10041002' },
          //   { text: '已激活', value: '10041001' }
          // ],
          render: props => {
            let res = '';
            switch (props.row.ActivationFlag) {
              case '10041001':
                res = '已激活';
                break;
              case '10041002':
                res = '待激活';
                break;
            }
            return <span>{res}</span>;
          }
        },
        {
          title: '客户代码',
          dataIndex: 'CustomerNO',
          showOverflowTooltip: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8249'),
          dictItems: this.createDictList('8249')
        },
        {
          title: '客户名称',
          dataIndex: 'CustomerName',
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '移动电话',
          dataIndex: 'Mobile',
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '牌照号',
          dataIndex: 'license',
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '底盘号',
          dataIndex: 'Vin',
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        }
      ];
    },
    async getQueryBookingInformation() {
      try {
        let res = await getAllUser();
        this.serviceAdvisorData = res.data.map(x => ({ text: x.employeeName, value: x.userId }));
      } catch (error) {}
    },
    getEmployeeName(userId) {
      const item = this.serviceAdvisorData.find(x => {
        return x.value == userId;
      });
      return item ? item.text : '';
    },
    async getStorage() {
      // const res = await findStorageCode();
      // this.topFilterList.find(item => item.fieldName === 'STORAGE_CODE').itemList = res.data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
    },
    // 点击搜索按钮
    async changeHandle(val) {
      // this.fetchParams.xhrAbort = true;
      // this.fetchParams = Object.assign({}, val, { xhrAbort: false });
      let res = await listQRCode(val);
      this.tableDataList = [];
      this.tableDataList = res.data.rows;
      this.lockData = [];
      res.data.rows.forEach(element => {
        if (element.ActivationFlag == '10041001') {
          this.lockData.push(element);
        }
      });
      // console.log(this.lockData, '锁定数据');
      // this.$refs.lackDetailTable.EXECUTE_INSERT(res.data.rows);
      // this.setEditable(lockData);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    }
    // async saveClick() {
    //   if (this.partColumns.length <= 0) {
    //     this.$notify.error({ title: '提示信息', message: '请先选择数据!' });
    //   } else {
    //     let obj = {
    //       tableList: this.partColumns
    //     };
    //     // let res = await saveShortPart(obj).then(() => {
    //     //   this.fetchParams = Object.assign({}, this.fetchParams); // 刷新表格
    //     // });
    //   }
    // }
  }
};
</script>

<style lang="less" scoped></style>
